package com.leetcode;

/**
 * 在排序数组中查找元素的第一个和最后一个位置
 *
 * @author winson
 * @create 2022-04-01 10:54
 */
public class SearchRangeSolution {

    /**
     * 如何查询元素的第一个位置
     * 二分查找元素，要找第一个元素，发现符合条件时，继续往左侧查找
     * @param nums
     * @param target
     * @return
     */
    public int[] searchRange(int[] nums, int target) {
        int firstIndex = binarySearch(nums, target, true);
        int lastIndex = binarySearch(nums, target, false) - 1;
        if (firstIndex <= lastIndex && lastIndex < nums.length && nums[firstIndex] == target && nums[lastIndex] == target) {
            return new int[]{firstIndex, lastIndex};
        }
        return new int[]{-1,-1};
    }

    public int binarySearch(int[] nums, int target, boolean lower) {
        int ans = -1;
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > target || (lower && nums[mid] >= target)) {
                right = mid - 1;
                ans = mid;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }
}
